package com.datareport.data.security;

import cn.hutool.core.util.StrUtil;
import com.datareport.data.Utils.JwtUtils;
import com.datareport.data.dto.ResultDTO;
import com.datareport.data.entity.User;
import com.datareport.data.exception.CustomizeErrorCode;
import com.datareport.data.exception.CustomizeException;
import com.datareport.data.service.UserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.TreeSet;

@Slf4j
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
   @Autowired
   JwtUtils jwtUtils;

   @Autowired
   UserService userService;

   @Autowired
   UserDetailServiceImpl userDetailService;

   public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
      super(authenticationManager);
   }
   @Override
   protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
      String jwt = request.getHeader(jwtUtils.getHeader());
      if (StrUtil.isBlankOrUndefined(jwt)) {
         chain.doFilter(request, response);
         return;
      }
      //token异常
      Claims claim = jwtUtils.getClaimByToken(jwt);
      if (claim == null) {
        throw new CustomizeException(CustomizeErrorCode.TOKEN_NOT_FOUND);
      }

      //token过期
      if (jwtUtils.isTokenExpired(claim)) {
         throw new CustomizeException(CustomizeErrorCode.LOGIN_HAS_EXPIRED);
      }


      String username = claim.getSubject();
      // 获取用户的权限等信息，做权限拦截时用到

      User user = userService.getByName(username);
      UsernamePasswordAuthenticationToken token
              = new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(user.getId()));

      SecurityContextHolder.getContext().setAuthentication(token);

      chain.doFilter(request, response);

   }
}